import { defineStore } from 'pinia';

const subscribe = defineStore({
  id: 'subscribe',
  state: () => ({
    tmplId:{
		cancelOrder:['Tw7S2e-Qm64QA8mtmJZuUoRcV76jLRssAlvBbbGC718','mVQqusUDrAknKwgcL2fJNUaNkD9ARiitWnnkjxbjXos'],  //取消订单的消息
		scheduleOrder:['mVQqusUDrAknKwgcL2fJNUaNkD9ARiitWnnkjxbjXos'],  //订单进度
	}
  }),
  actions: {
	/**
	 * 订阅消息，权限判断
	 */
	subscribeMessage(tmplKey = '') {
		let _this = this
		let tmplId = _this.tmplId[tmplKey]
		console.log('tmplId',tmplId);
		return new Promise((resolve, reject) => {
			uni.requestSubscribeMessage({
				tmplIds:tmplId,
				success: res => {
					for (var i = 0; i < tmplId.length; i++) {						
						if (res[tmplId[i]] === 'accept') {
							if(tmplId.length <= 1) {
								uni.showToast({
									title:'通知消息订阅成功',
									icon:'none'
								})
							}
							resolve(true)
						} else if (res[tmplId[i]] == 'reject') {
							uni.showModal({
								title: '订阅消息',
								content: '未开启消息订阅通知，是否去开启',  
								confirmText: '开启授权',
								confirmColor: '#345391',
								cancelText: '仍然拒绝',
								cancelColor: '#999999',
								success(res) {
									if (res.confirm) {
									
										uni.openSetting({
											success(res) {
												console.log(res.authSetting)
												resolve(true)
											},
											fail(err) {
												//失败
												resolve(false)
												console.log(err)
											}
										})
									} else if (res.cancel) {
										resolve(false)
										console.log('用户点击取消')
									}
								}
							})
						} else {
							resolve(false)
							console.log(res,'没有接受消息');
						}
					}
				},
				fail(err) {
					//失败
					uni.showModal({
						title: '订阅消息',
						content: '您当前拒绝接受消息通知，是否去开启',
						confirmText: '开启授权',
						confirmColor: '#345391',
						cancelText: '仍然拒绝',
						cancelColor: '#999999',
						success(res) {
							if (res.confirm) {
								console.log('用户点击确定')
								uni.openSetting({
									success(res) {
										resolve(true)
										console.log(res.authSetting)
									},
									fail(err) {
										//失败
										resolve(false)
										console.log(err)
									}
								})
							} else if (res.cancel) {
								resolve(false)
								console.log('用户点击取消')
							}
						}
					})
					console.log(err, tmplId, '失败了')
				}
			})
		})
	}
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'subscribe-store',
        paths: ['lastTimer', 'advHistory'],
      },
    ],
  },
});

export default subscribe;
